package com.lyy.system.controller;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lyy.response.Result;
import com.lyy.system.entity.RandomInfo;
import com.lyy.system.entity.VerifyCode;
import com.lyy.system.mapper.RandomInfoMapper;
import com.lyy.system.service.IVerifyCodeGen;
import com.lyy.system.service.impl.SimpleCharVerifyCodeGenImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@RestController
@RequestMapping("/verifCode")
@Api(value = "验证码",tags = "验证码")
public class VerifyCodeController {

    @Autowired
    private RandomInfoMapper randomInfoMapper;
    @ApiOperation(value = "验证码")
    @GetMapping("/getVerifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
        String data=null;
       if (request.getParameter("data")!=null){
           data=new String(request.getParameter("data").trim().getBytes("ISO-8859-1"),"utf-8");
       }
        System.out.println("时间---------------"+ data);
        try {
            //设置长宽
            VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
            String code = verifyCode.getCode();
            System.out.println("验证码---------------"+ code);
            //将VerifyCode绑定session
            request.getSession().setAttribute("VerifyCode", code);
            //设置响应头
            response.setHeader("Pragma", "no-cache");
            //设置响应头
            response.setHeader("Cache-Control", "no-cache");
            //在代理服务器端防止缓冲
            response.setDateHeader("Expires", 0);
            //设置响应内容类型
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
            RandomInfo randomInfo =new RandomInfo();
            randomInfo.setDciCheckno(data);
            randomInfo.setDciCode(code);
            randomInfo.setDciCreatetime(new Date());
            randomInfoMapper.insert(randomInfo);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
